package jsyf.com.util;


import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.*;
import com.google.common.io.Closeables;
import org.apache.commons.lang3.time.DateUtils;
import org.aspectj.util.FileUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

public class OssClient {

    private static final Logger LOG = LoggerFactory.getLogger(OSSClient.class);
    //常量接口
    private static final int YEARS_TO_EXPIRE = 10;
    //阿里云OSS账户
    private static final String ENDPOINT = "https://oss-cn-beijing.aliyuncs.com";
    private static final String ACCESS_KEY_ID = "flvEKGlSP2gwEMcw";
    private static final String ACCESS_KEY_SECRET = "dU3Yz65n6lXEjdLLmzDOjQjnwJZAyo";
    private static final String BUCKET_NAME = "office-auto";

    // 按每天的时间创建文件夹
    private static final Date date = new Date();
    //首先是按年-月创建
    private static final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMM");
    private static final String yearMonth = simpleDateFormat.format(date);
    //在按照时间创建
    private static final Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT+08:00"));
    private static final int dayTime = calendar.get(Calendar.DAY_OF_MONTH);

    //域名与IP常量
    public static final String ESH_OSS_DOMAIN = "https://office-auto.oss-cn-beijing.aliyuncs.com/";


    public static OSSClient getOssClient() {
        return new OSSClient(ENDPOINT, ACCESS_KEY_ID, ACCESS_KEY_SECRET);
    }

    /**
     * 上传到OSS服务器  如果同名文件会覆盖服务器上的
     *
     * @param instream 文件流
     * @param fileName 文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public static String uploadFileToOSS(InputStream instream, String fileName) {
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setContentType(contentType(fileName.substring(fileName.lastIndexOf("."))));
            String name = "images/" + yearMonth + "/" + dayTime + "/" + fileName;
            //上传文件
            getOssClient().putObject(BUCKET_NAME, name, instream, objectMetadata);
            //获取文件服务器url
            String url = getUrl(name).split("\\?")[0];
            return url;
        } catch (Exception e) {
            //LOG.warn("OSSClient@uploadFileToOSS", e);
            return "";
        } finally {
            Closeables.closeQuietly(instream);
        }
    }


    /**
     * 文件下载
     *
     * @param myKey
     * @param
     * @throws Exception
     */
    public static InputStream downloadFile(String myKey) throws Exception {
        // 创建OSSClient实例
        InputStream inputStream = null;
        // 下载object到文件
        try {
            myKey = myKey.replace(ESH_OSS_DOMAIN, "");
            OSSObject ossObject = getOssClient().getObject(BUCKET_NAME, myKey);
            InputStream in = ossObject.getObjectContent();
            return in;
        } catch (OSSException oe) {
            oe.printStackTrace();
            throw new Exception(oe.getErrorMessage());
        } catch (ClientException ce) {
            ce.printStackTrace();
            throw new Exception(ce.getErrorMessage());
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception(e.getMessage());
        } finally {
            getOssClient().shutdown();// 关闭client
        }
    }

    /**
     * @Author:CCP
     * @Date:2017/5/5 16:01
     * @Description: 判断OSS服务文件上传时文件的contentType
     * @User:
     */
    /**
     * @param fileType
     * @return String
     * @MethodName: contentType
     * @Description: 获取文件类型
     */
    private static String contentType(String fileType) {
        fileType = fileType.toLowerCase();
        String contentType = "";
        switch (fileType) {
            case ".bmp":
                contentType = "image/bmp";
                break;
            case ".gif":
                contentType = "image/gif";
                break;
            case ".png":
            case ".jpeg":
            case ".jpg":
                contentType = "image/jpeg";
                break;
            case ".html":
                contentType = "text/html";
                break;
            case ".txt":
                contentType = "text/plain";
                break;
            case ".vsd":
                contentType = "application/vnd.visio";
                break;
            case ".ppt":
            case ".pptx":
                contentType = "application/vnd.ms-powerpoint";
                break;
            case ".doc":
            case ".docx":
                contentType = "application/msword";
                break;
            case ".xml":
                contentType = "text/xml";
                break;
            case ".mp4":
                contentType = "video/mp4";
                break;
            default:
                contentType = "application/octet-stream";
                break;
        }
        return contentType;
    }

    /**
     * 获取Url链接
     *
     * @param key
     * @return
     */
    public static String getUrl(String key) {
        // 生成URL
        Date expiration = DateUtils.addYears(new Date(), YEARS_TO_EXPIRE);
        URL url = getOssClient().generatePresignedUrl(BUCKET_NAME, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }


}
